'''
Created on Dec 2, 2011

@author: anorberg
'''
from __future__ import division

import loadRfAceResult
import tsv
import sys

def main(infile, outfile, sortIndex = None):
    records = [record for record in loadRfAceResult.loadRfAceResultFile(infile)]
    outputWriter = tsv.TsvWriter(open(outfile, "w"), '\t')
    
    if sortIndex is not None:
        records.sort(key = lambda x: float(x[sortIndex]))
    
    for column in loadRfAceResult.ASSOC_12_2_2011:
        outputWriter.addColumn(column, lambda x, lockedColumn = column : x[1][lockedColumn])
    total = len(records)
    outputWriter.addColumn("Percentile Rank", lambda x : x[0]/total)
    
    n = 0
    for record in records:
        outputWriter.printRecord((n, record))
        n += 1
    outputWriter.flush()
    

if __name__ == '__main__':
    """
    PARAMS:
        1 infile
        2 outfile
        3 sort-column (or -1 for "don't")
    """
    if len(sys.argv) >= 4:
        index = sys.argv[3]
        try:
            index = int(index)
            if index < 0:
                index = None
        except TypeError:
            index = sys.argv[3]
        main(sys.argv[1], sys.argv[2], index)
    else:
        main(sys.argv[1], sys.argv[2])